import React, {Component} from 'react';
import {Button, Form, Input, Row, Col, Table, Pagination, DatePicker, Select} from 'antd';
import moment from 'moment';
import {storage,excel} from "../value";
import app from '../AppMethod';
import {config} from "../config";
import {Consumer} from "../store";

const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;
const Option = Select.Option;

class storageManage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            pagination: {
                current: 0,
                total: 0,
                pagination: 0
            },
            allPage: 0,
            data: [],
            searchData: {}
        }
    };

    columns = [
        {
            title: '厂家',
            dataIndex: 'storage_factory'
        },
        {
            title: '订单号',
            dataIndex: 'storage_num'
        },
        {
            title: '预计来货日期',
            dataIndex: 'storage_time'
        },
        {
            title: '实际来货日期',
            dataIndex: 'storage_real_time'
        },
        {
            title: '预计金额',
            dataIndex: 'storage_money'
        },
        {
            title: '实际金额',
            dataIndex: 'storage_real_money'
        },
        {
            title: '预计件数',
            dataIndex: 'storage_package'
        },
        {
            title: '实际件数',
            dataIndex: 'storage_real_package'
        },
        {
            title: '预计散包数',
            dataIndex: 'storage_single'
        },
        {
            title: '实际散包数',
            dataIndex: 'storage_real_single'
        },
        {
            title: '收货人',
            dataIndex: 'storage_receive_name'
        },
        {
            title: '卸货人',
            dataIndex: 'storage_unload_name'
        },
        {
            title: '下单日期',
            dataIndex: 'storage_order_time'
        },
        {
            title: '状态',
            dataIndex: 'storage_status',
            render: storage_status => {
                let text = '';
                if (storage_status == 0) {
                    text = '待入库';
                } else if (storage_status == 1) {
                    text = '已入库';
                } else if (storage_status == 2) {
                    text = '已过账';
                }
                return (
                    <span>{text}</span>
                )
            }
        },
        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                return (
                    <span style={{color: '#1890ff', cursor: 'pointer', marginLeft: '10px'}}
                          onClick={() => this.handleGetDetail(data.storage_id)}>详情</span>
                )
            }
        }
    ];

    render() {
        return (
            <div>
                    <Row>
                        <SearchLists
                            clickSearch={(value) => {
                                this.handleGetSearch(value)
                            }}
                            handleReset={() => this.handleReset()}
                            handleRefresh={()=>this.handleRefresh()}
                            handleExport={(values)=>this.handleExport(values)}
                        >
                        </SearchLists>
                    </Row>
                    <Row style={{marginTop: '20px'}}>
                        <Table
                            columns={this.columns}
                            rowKey={record => record.storage_id}
                            loading={this.state.loading}
                            dataSource={this.state.data}
                            pagination={false}
                        >
                        </Table>
                    </Row>
                    <Row style={{marginTop: '20px'}}>
                        <Col span={12} style={{fontSize: '15px'}}>
                            共 {this.state.pagination.total} 条记录 第 {this.state.pagination.current} / {this.state.allPage}
                            页
                        </Col>
                        <Col span={12} style={{textAlign: 'right'}}>
                            <Pagination {...this.state.pagination} showSizeChanger={true} showQuickJumper={true}
                                        hideOnSinglePage={false}
                                        onChange={(page, pageSize) => this.handlePageChange(page, pageSize)}
                                        onShowSizeChange={(current, size) => this.handleSizeChange(current, size)}/>
                        </Col>
                    </Row>
                </div>
        )
    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({menuType: "入库管理"});
        this.handleSearchOrderList();
    }

    componentWillUnmount() {
        this.setState = (count, callback) => {
            return;
        }
    }

    /**
     * 搜索入库订单列表
     * @param data
     */
    handleSearchOrderList(data = {page: 1, size: 10}) {
        this.setState({loading: true});
        app.post(storage.SEARCH_STORAGELIST, data).then((result) => {
            if (result.code === 1) {
                let count = result.data.count;
                let pagination = {
                    current: data.page,
                    pageSize: data.size,
                    total: count
                };
                let allPage;
                if (count % data.size > 0) {
                    allPage = parseInt(count / data.size) + 1;
                } else {
                    allPage = count / data.size;
                }
                let orderData = result.data.dataSet;
                for (let i = 0; i < orderData.length; i++) {
                    orderData[i].storage_time = orderData[i].storage_time === null ? '' : moment(orderData[i].storage_time).format('YYYY-MM-DD');
                    orderData[i].storage_real_time = orderData[i].storage_real_time === null ? '' : moment(orderData[i].storage_real_time).format('YYYY-MM-DD');
                    orderData[i].storage_order_time = orderData[i].storage_order_time === null ? '' : moment(orderData[i].storage_order_time).format('YYYY-MM-DD');
                }
                this.setState({allPage, pagination, data: orderData, loading: false});
            } else {
                let pagination = {
                    current: 0,
                    pageSize: 0,
                    total: 0
                };
                let allPage = 0;
                this.setState({allPage, pagination, data: [], loading: false});
            }
        })
    };

    /**
     * 根据搜索条件搜索订单列表
     * @param value
     */
    handleGetSearch(value) {
        let times = value.storage_order_time;
        let storage_order_time_start = undefined;
        let storage_order_time_end = undefined;
        if (times != undefined&&times.length>0) {
            storage_order_time_start = moment(times[0]._d).format('YYYY-MM-DD');
            storage_order_time_end = moment(times[1]._d).format('YYYY-MM-DD');
        }

        let times1 = value.storage_real_time;
        let storage_real_time_start = undefined;
        let storage_real_time_end = undefined;
        if (times1 != undefined&&times1.length>0) {
            storage_real_time_start = moment(times1[0]._d).format('YYYY-MM-DD');
            storage_real_time_end = moment(times1[1]._d).format('YYYY-MM-DD');
        }
        let searchData = {
            storage_num: value.storage_num,
            storage_factory: value.storage_factory,
            storage_status: value.storage_status,
            storage_real_time_start: storage_real_time_start,
            storage_real_time_end: storage_real_time_end,
            storage_order_time_start: storage_order_time_start,
            storage_order_time_end: storage_order_time_end
        };
        console.log(JSON.stringify(searchData));
        this.setState({searchData});
        searchData.page = 1;
        searchData.size = this.state.pagination.pageSize || 10;
        this.handleSearchOrderList(searchData);
    };

    /**
     * 处理重置事件
     */
    handleReset() {
        this.setState({searchData: {}});
        this.handleSearchOrderList();
    };

    /**
     * 处理分页跳转事件
     * @param page
     * @param size
     */
    handlePageChange(page, size) {
        let data = this.state.searchData;
        data.page = page;
        data.size = size;
        this.handleSearchOrderList(data);
    };

    /**
     * 处理页数变化事件
     * @param current
     * @param size
     */
    handleSizeChange(current, size) {
        let data = this.state.searchData;
        data.page = current;
        data.size = size;
        this.handleSearchOrderList(data);
    };

    /**
     * 处理刷新入库草稿单事件
     */
    handleRefresh() {
        const _this=this;
        app.post(storage.FLASH_STORAGE, {}).then((result) => {
            if (result.code === 1) {
                app.alert(result.msg, 'success', 3);
                _this.handleReset();
            } else {
                app.alert(result.msg, 'error', 3);
            }
        })
    };

    /**
     * 处理跳转到入库单详情页面
     * @param id
     */
    handleGetDetail(id) {
        this.props.history.push(`/index/storageDetails/${id}`);
    };

    /**
     * 处理导出Excel事件
     * @param value
     */
    handleExport(value){
        let times = value.storage_order_time;
        let storage_order_time_start = undefined;
        let storage_order_time_end = undefined;
        if (times != undefined&&times.length>0) {
            storage_order_time_start = moment(times[0]._d).format('YYYY-MM-DD');
            storage_order_time_end = moment(times[1]._d).format('YYYY-MM-DD');
        }

        let times1 = value.storage_real_time;
        let storage_real_time_start = undefined;
        let storage_real_time_end = undefined;
        if (times1 != undefined&&times1.length>0) {
            storage_real_time_start = moment(times1[0]._d).format('YYYY-MM-DD');
            storage_real_time_end = moment(times1[1]._d).format('YYYY-MM-DD');
        }
        let searchData = {
            storage_num: value.storage_num,
            storage_factory: value.storage_factory,
            storage_status: value.storage_status,
            storage_real_time_start: storage_real_time_start,
            storage_real_time_end: storage_real_time_end,
            storage_order_time_start: storage_order_time_start,
            storage_order_time_end: storage_order_time_end
        };
        let params=app.getParams(searchData);
        if(params.length>0){
            window.location.href = config.serverUrl + excel.EXPORT_STORAGELIST +'?'+ params;
        }else{
            window.location.href = config.serverUrl + excel.EXPORT_STORAGELIST;
        }
    }
};

class SearchList extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    };
    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };
    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <div>
                <Row>
                    <Form className="login-form">
                        <Row>
                            <Col span={7}>
                                <FormItem label="订单号" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('storage_num')(
                                            <Input type="text" placeholder="请输入" onPressEnter={()=>this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={7}>
                                <FormItem label="厂家" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('storage_factory')(
                                            <Input type="text" placeholder="请输入" onPressEnter={()=>this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={5}>
                                <FormItem label="状态" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('storage_status')(
                                            <Select placeholder="请选择" onChange={(value)=>this.handleStatusOnChange(value)}>
                                                <Option value={'0'}>待入库</Option>
                                                <Option value={'1'}>已入库</Option>
                                                <Option value={'2'}>已过账</Option>
                                            </Select>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={5} style={{float: 'right'}}>
                                <Button type="primary"
                                        onClick={() => this.handleSearchComplain()}
                                >
                                    查询
                                </Button>
                                <Button type="default"
                                        onClick={() => this.handleReset()}
                                        style={{marginLeft: '10px'}}
                                >
                                    重置
                                </Button>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={7}>
                                <FormItem label="实际来货日期" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('storage_real_time')(
                                            <RangePicker
                                                ranges={{
                                                    Today: [moment(), moment()],
                                                    'This Month': [moment(), moment().endOf('month')]
                                                }}
                                                format="YYYY/MM/DD"
                                                onChange={(dates,dateStrings)=>this.handleRealTimeOnChange(dates,dateStrings)}
                                            />
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={7}>
                                <FormItem label="下单日期" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('storage_order_time')(
                                            <RangePicker
                                                ranges={{
                                                    Today: [moment(), moment()],
                                                    'This Month': [moment(), moment().endOf('month')]
                                                }}
                                                format="YYYY/MM/DD"
                                                onChange={(dates,dateStrings)=>this.handleOrderTimeOnChange(dates,dateStrings)}
                                            />
                                        )
                                    }
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Row>
                <Row>
                    <Button type='primary' onClick={()=>this.handleExport()}>导出Excel</Button>
                    <Button type='primary' style={{marginLeft: '10px'}}
                            onClick={() => this.handleRefresh()}>刷新</Button>
                </Row>
            </div>
        )
    };

    componentDidMount() {

    };

    /**
     * 获取搜索条件
     */
    handleSearchComplain() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.clickSearch(values);
            }
        })
    };

    /**
     * 处理重置按钮事件
     */
    handleReset() {
        this.props.form.resetFields();
        this.props.handleReset();
    };

    /**
     * 获取导出Excel条件
     */
    handleExport(){
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.handleExport(values);
            }
        })
    };

    /**
     * 处理刷新入库草稿单事件
     */
    handleRefresh(){
        this.props.handleRefresh();
    };

    /**
     * 处理输入框按下回车键的事件
     */
    handleOnPressEnter(){
        //调用获取搜索条件的函数
        this.handleSearchComplain();
    };

    /**
     * 处理状态下拉框选择变化事件
     * @param value
     */
    handleStatusOnChange(value){
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.storage_status=value;
                this.props.clickSearch(values);
            }
        })
    };

    /**
     * 处理实际来货日期选择框变化事件
     */
    handleRealTimeOnChange(dates,dateStrings){
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.storage_real_time=dates;
                this.props.clickSearch(values);
            }
        })
    };

    /**
     * 处理下单日期选择框变化事件
     */
    handleOrderTimeOnChange(dates,dateStrings){
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.storage_order_time=dates;
                this.props.clickSearch(values);
            }
        })
    };
}

const SearchLists = Form.create()(SearchList);
const StorageManages = Form.create()(storageManage);
export default prop => (
    <Consumer>
        {
            props => (
                <StorageManages {...prop} {...props}/>
            )
        }
    </Consumer>
);